Popular Searches
Popular Course Categories
Popular Courses

Using Logical Operators in Conditional Expressions

Using Logical Operators in Conditional Expressions

Conditional Statements and Decision Making

Using Logical Operators in Conditional Expressions in Python

Course: Python Programming

Topic: Using Logical Operators in Conditional Expressions

Course Link: Python Training Course – JustAcademy

Demo Link: Register for a Course Demo

Website: JustAcademy Official Website


1. Introduction to Logical Operators

Logical operators in Python are used to combine conditions, reverse truth values, and control the flow of a program. They help developers create more flexible decision-making expressions by checking multiple requirements together.

For example, an online shopping application might provide a discount when a customer is a member and the purchase amount meets a minimum requirement. A login system might allow access only when a username is valid and an account is active.

Python provides three primary logical operators:

  • and – checks whether both conditions are truthy.
  • or – checks whether at least one condition is truthy.
  • not – reverses the truth value of a condition.

Logical operators are commonly used with comparison operators, conditional statements, loops, and conditional expressions.

age = 25
has_id = True

if age >= 18 and has_id:
    print("Access granted")
else:
    print("Access denied")

Output:

Access granted

In this example, access is granted only when the person is at least 18 years old and has identification.

2. Learning Objectives

After completing this topic, learners should be able to:

  • Understand logical operators and their role in conditional expressions.
  • Use and, or, and not correctly.
  • Understand truth tables and Boolean logic.
  • Combine logical operators with comparison operators.
  • Apply logical operators in if, elif, and else statements.
  • Understand operator precedence and parentheses.
  • Explain short-circuit evaluation.
  • Understand truthy and falsy values.
  • Identify common logical errors.
  • Build practical decision-making programs using compound conditions.

3. What Is a Conditional Expression?

A conditional expression evaluates a condition and uses its result to make a decision or determine a value. In an if statement, Python executes a particular block depending on whether the condition is truthy or falsy.

Logical operators make conditional expressions more powerful by combining multiple requirements into a single expression.

Example Without Logical Operators

age = 22
has_id = True

if age >= 18:
    if has_id:
        print("Registration allowed")

Example With a Logical Operator

age = 22
has_id = True

if age >= 18 and has_id:
    print("Registration allowed")

Output:

Registration allowed

The second example combines both requirements in one condition, making the code more concise.

4. The and Operator

The and operator combines two conditions. The overall condition is truthy only when both operands are truthy.

Syntax

condition1 and condition2

Truth Table

Condition A Condition B A and B
True True True
True False False
False True False
False False False

Example: Student Eligibility

marks = 75
attendance = 85

if marks >= 40 and attendance >= 75:
    print("Student is eligible")
else:
    print("Student is not eligible")

Output:

Student is eligible

Both conditions are true, so the first block executes.

Example: Checking a Number Range

number = 50

if number >= 1 and number <= 100:
    print("Number is within the range")
else:
    print("Number is outside the range")

Output:

Number is within the range

Python also supports chained comparisons, so the condition can be written more clearly as 1 <= number <= 100.

5. The or Operator

The or operator combines two conditions. The overall condition is truthy when at least one operand is truthy.

Syntax

condition1 or condition2

Truth Table

Condition A Condition B A or B
True True True
True False True
False True True
False False False

Example: Discount Eligibility

is_member = False
purchase_amount = 2500

if is_member or purchase_amount >= 2000:
    print("Discount available")
else:
    print("No discount available")

Output:

Discount available

The customer is not a member, but the purchase amount meets the minimum requirement. Therefore, the condition is true.

Example: Login Options

login_with_email = False
login_with_phone = True

if login_with_email or login_with_phone:
    print("Login method selected")
else:
    print("Choose a login method")

Output:

Login method selected

The or operator is useful when a user can satisfy a requirement through one of several alternatives.

6. The not Operator

The not operator reverses the truth value of a condition. If the condition is true, not makes it false; if the condition is false, not makes it true.

Syntax

not condition

Truth Table

Condition not Condition
True False
False True

Example: Account Status

is_blocked = False

if not is_blocked:
    print("Account is active")
else:
    print("Account is blocked")

Output:

Account is active

Example: Checking an Empty List

cart = []

if not cart:
    print("Your shopping cart is empty")
else:
    print("Items are available in your cart")

Output:

Your shopping cart is empty

The not operator is often used to check whether a condition is false or a collection is empty.

7. Combining Multiple Logical Operators

Python allows multiple logical operators to be used in the same expression. This is useful when a decision depends on several conditions.

Example: Employee Bonus Eligibility

performance_score = 90
years_of_service = 5
attendance = 95

if performance_score >= 85 and years_of_service >= 3 and attendance >= 90:
    print("Employee qualifies for a bonus")
else:
    print("Employee does not qualify for a bonus")

Output:

Employee qualifies for a bonus

All three conditions must be satisfied because they are joined by and.

Example: Multiple Ways to Qualify

is_premium_member = False
purchase_amount = 5000
has_coupon = True

if is_premium_member or purchase_amount >= 3000 or has_coupon:
    print("Customer qualifies for an offer")
else:
    print("No offer available")

Output:

Customer qualifies for an offer

Only one of the conditions needs to be true for the combined expression to be truthy.

8. Operator Precedence in Logical Expressions

Operator precedence determines which operations Python evaluates first when an expression contains multiple operators.

For the logical operators covered in this topic, the order from highest to lowest precedence is:

  1. not
  2. and
  3. or

Comparison operators such as ==, >, and <= have higher precedence than not, and, and or.

Example

result = True or False and False
print(result)

Output:

True

Python evaluates False and False first, producing False. It then evaluates True or False, which produces True.

Using Parentheses

Parentheses help make the intended order of evaluation explicit.

age = 20
has_id = False
has_permission = True

result = (age >= 18 and has_id) or has_permission
print(result)

Output:

True

In this example, the final result is true because has_permission is true, even though the first grouped condition is false.

9. Short-Circuit Evaluation

Short-circuit evaluation means Python stops evaluating a logical expression when the final result is already determined.

  • With and, if the first operand is falsy, the second operand is not evaluated.
  • With or, if the first operand is truthy, the second operand is not evaluated.

Example: Short-Circuit with and

def check():
    print("Function executed")
    return True

result = False and check()
print(result)

Output:

False

The function is not executed because the first operand is false and the overall result of and is already determined.

Example: Short-Circuit with or

def check():
    print("Function executed")
    return False

result = True or check()
print(result)

Output:

True

The function is not executed because the first operand is true and the overall result of or is already determined.

Practical Use: Avoiding Division by Zero

denominator = 0

if denominator != 0 and 10 / denominator > 1:
    print("Condition satisfied")
else:
    print("Cannot divide by zero or condition is false")

Output:

Cannot divide by zero or condition is false

Because the first condition is false, Python does not evaluate 10 / denominator. This prevents a division-by-zero error.

10. Truthy and Falsy Values

Python conditions do not always need to contain explicit Boolean values. Python evaluates many types of values according to their truthiness.

Value Truth Value
True Truthy
False Falsy
0 Falsy
1 Truthy
"" Falsy
"Python" Truthy
[] Falsy
[1, 2] Truthy
None Falsy

Example

username = ""

if username:
    print("Username provided")
else:
    print("Username is empty")

Output:

Username is empty

Empty strings, empty collections, zero, and None are common falsy values. Most other values are truthy. Some user-defined objects can customize their truth value.

11. Logical Operators in Conditional Expressions

A Python conditional expression is a compact way to select one of two values based on a condition. Its general syntax is:

value_if_true if condition else value_if_false

Logical operators can be used inside the condition to combine requirements.

Example: Access Status

age = 25
has_id = True

status = "Access granted" if age >= 18 and has_id else "Access denied"

print(status)

Output:

Access granted

Example: Exam Result

marks = 75
attendance = 80

result = "Pass" if marks >= 40 and attendance >= 75 else "Fail"

print(result)

Output:

Pass

Example: Multiple Alternatives

is_weekend = True
is_holiday = False

day_status = "Day off" if is_weekend or is_holiday else "Working day"

print(day_status)

Output:

Day off

Conditional expressions are useful for short assignments. When conditions become complex, use a regular if-else statement to improve readability.

12. Difference Between Logical and Bitwise Operators

Logical operators and bitwise operators have different purposes. Logical operators work with truth values and conditions, while bitwise operators perform operations on individual bits of integer values or use overloaded behavior for supported objects.

Logical Operator Related Bitwise Operator Purpose
and & Logical conjunction versus bit-level AND.
or | Logical disjunction versus bit-level OR.
not ~ Logical negation versus bitwise inversion.

Example

a = True
b = False

print(a and b)
print(5 & 3)

Output:

False
1

The first expression evaluates a logical condition. The second performs a bitwise AND operation on the binary representations of two integers.

Important: Use and, or, and not for ordinary conditional logic. Do not substitute &, |, or ~ for them without understanding the difference.

13. Common Mistakes When Using Logical Operators

Mistake Problem Correct Approach
Using & instead of and Bitwise operations do not behave like logical short-circuit operators. Use and for ordinary conditions.
Using or when both conditions are required The condition may pass when only one requirement is satisfied. Use and when both requirements must hold.
Incorrect operator precedence assumptions The expression may be evaluated in an unintended order. Use parentheses to clarify complex conditions.
Writing incomplete comparisons A condition may not check the intended range. Use expressions such as 18 <= age <= 60.
Using not incorrectly The condition may be reversed unintentionally. Read the negated expression carefully.
Ignoring short-circuit behavior An unsafe expression may execute when it should not. Place safety checks before dependent operations.
Assuming and and or always return Boolean values They can return one of their operands instead. Use bool() if an explicit Boolean value is required.

14. Real-World Example: Online Shopping Eligibility

Online shopping applications often use logical conditions to determine whether a customer qualifies for free shipping or a discount.

purchase_amount = 1800
is_premium_member = True
has_coupon = False

if purchase_amount >= 2000 or is_premium_member or has_coupon:
    print("Customer qualifies for a special offer")
else:
    print("Customer does not qualify for a special offer")

Output:

Customer qualifies for a special offer

The customer qualifies because the premium membership condition is true.

15. Real-World Example: Login Validation

Login workflows often combine conditions to determine whether a user should be allowed to continue.

username_correct = True
password_correct = True
account_active = True

if username_correct and password_correct and account_active:
    print("Login successful")
else:
    print("Login failed")

Output:

Login successful

All three requirements must be satisfied. This example demonstrates decision logic only; real authentication systems require secure credential verification and additional security protections.

16. Real-World Example: Weather Recommendation

Logical operators can combine environmental conditions to recommend an activity.

temperature = 28
is_raining = False

if temperature >= 25 and not is_raining:
    print("Good weather for outdoor activities")
else:
    print("Consider an indoor activity")

Output:

Good weather for outdoor activities

The temperature requirement must be satisfied, and the rain condition must be false.

17. Practice Exercises

Try solving these exercises before reviewing the solutions.

  1. Write a program that checks whether a number is between 10 and 50, inclusive.
  2. Write a program that allows registration when a person is at least 18 and has an identity document.
  3. Write a program that grants a discount when a customer is a member or spends at least 3000.
  4. Write a program that checks whether a user is not blocked.
  5. Write a program that verifies whether marks are at least 40 and attendance is at least 75.
  6. Write a program using not to check whether a shopping cart is empty.
  7. Predict the result of True or False and False.
  8. Demonstrate short-circuit evaluation using a function that prints a message.
  9. Write a conditional expression that returns "Eligible" when a person's age is at least 18 and "Not eligible" otherwise.
  10. Write a program that allows access when a user has an administrator role or special permission.

18. Practice Exercise Solutions

Solution 1: Check a Number Range

number = 25

if 10 <= number <= 50:
    print("Within range")
else:
    print("Outside range")

Solution 2: Registration Eligibility

age = 20
has_id = True

if age >= 18 and has_id:
    print("Registration allowed")
else:
    print("Registration denied")

Solution 3: Discount Eligibility

is_member = False
purchase_amount = 3500

if is_member or purchase_amount >= 3000:
    print("Discount available")
else:
    print("No discount available")

Solution 4: Account Status

is_blocked = False

if not is_blocked:
    print("Account can be accessed")
else:
    print("Account access denied")

Solution 5: Exam Eligibility

marks = 70
attendance = 80

if marks >= 40 and attendance >= 75:
    print("Eligible")
else:
    print("Not eligible")

Solution 6: Empty Shopping Cart

cart = []

if not cart:
    print("Cart is empty")
else:
    print("Cart contains items")

Solution 7: Predict the Result

print(True or False and False)

Output:

True

The and operator has higher precedence than or, so the expression becomes True or (False and False).

19. Interview Questions and Answers

Q1. What are logical operators in Python?

Logical operators combine conditions or reverse truth values. The three primary logical operators are and, or, and not.

Q2. What is the difference between and and or?

and requires both operands to be truthy for the combined expression to be truthy. or requires at least one operand to be truthy.

Q3. What does the not operator do?

The not operator reverses the truth value of its operand and returns a Boolean result.

Q4. What is a truth table?

A truth table lists the possible truth values of input conditions and the resulting truth value of an operation.

Q5. What is short-circuit evaluation?

Short-circuit evaluation stops evaluating an expression when the result is already determined by the first operand.

Q6. What is the precedence of logical operators?

Among the three logical operators, not has the highest precedence, followed by and, then or.

Q7. Can logical operators return values other than True or False?

Yes. Python's and and or operators return one of their operands. The not operator returns a Boolean value.

Q8. How can logical operators be used with if statements?

They combine conditions so that a program can make decisions based on multiple requirements.

Q9. What is the difference between and and bitwise &?

and performs logical short-circuit evaluation, whereas & performs a bitwise AND operation for integers and may invoke overloaded behavior for other objects.

Q10. Why are parentheses useful in logical expressions?

Parentheses make the intended grouping explicit and improve readability, especially when multiple operators are combined.

20. Quick Revision Checklist

  • and requires both operands to be truthy.
  • or requires at least one operand to be truthy.
  • not reverses the truth value.
  • Logical operators can combine comparison expressions.
  • not has higher precedence than and, which has higher precedence than or.
  • Parentheses help clarify complex conditions.
  • Short-circuit evaluation can prevent unnecessary or unsafe operations.
  • Falsy values include zero, False, None, and empty collections.
  • and and or can return operands rather than Boolean values.
  • Logical operators work inside conditional statements and conditional expressions.
  • Testing different combinations of conditions helps identify logical errors.

21. Conclusion

Logical operators are essential for creating meaningful conditional expressions in Python. They allow programmers to combine conditions, evaluate alternatives, reverse truth values, and implement complex decision-making rules.

By understanding and, or, and not, along with truth tables, precedence, short-circuit evaluation, and truthy and falsy values, learners can write more accurate and readable programs.

Practice these concepts through eligibility checks, shopping discounts, login workflows, input validation, and other real-world examples to build a strong foundation in Python programming.


Learn Python with JustAcademy

Continue learning Python programming through the following resources:

Further reading: Python Official Documentation – Boolean Operations

whatsapp